package com.business.file.service;

import com.business.file.rabbitMq.RabbitMqSender;
import com.business.common.dto.R;
import com.business.common.enums.ErrorEnum;
import com.business.common.utils.FileUtil;
import com.business.common.utils.StrKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
public class FileService {

    private BlockingQueue<Runnable> delQueue = new LinkedBlockingQueue<>();

    private ThreadPoolExecutor delPool = new ThreadPoolExecutor(9, 36, 60, TimeUnit.SECONDS, delQueue);

    private Logger logger = LoggerFactory.getLogger(FileService.class);

    @Autowired
    private Environment env;

    @Value("${file.base-path}")
    private String basePath;

    @Autowired
    private RabbitMqSender rabbitMqSender;

    /**
     * 上传图片 并检查图片格式 和类型 大小
     *
     * @param fileUpload
     * @param module     资源文件类型，如用户头像 公司头像
     * @return data:路径
     * @throws IOException
     */
    public R<String> uploadImage(MultipartFile fileUpload, String module, String folder) {
        //获取文件上传目录
        String uploadPath = getUploadPath(module, folder);
        //获取文件名
        String fileName = fileUpload.getOriginalFilename();
        //重新生成文件名
        String newFileName = FileUtil.renameToUUID(fileName);
        String contentPath = env.getProperty("server.servlet.context-path");
        String fullFileName = contentPath + uploadPath + newFileName;
        FileOutputStream out = null;

        try {
            //将图片保存到static文件夹里
            String filePath = basePath + uploadPath + newFileName;
            File targetFile = new File(basePath + uploadPath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            File  file = new File(filePath);
            out = new FileOutputStream(file);
            out.write(fileUpload.getBytes());
            //压缩图片
            if(file.length() > 81920){
                rabbitMqSender.resizedImage(filePath);
            }
        } catch (Exception e) {
            logger.error("上传图片失败," + e.getMessage(), e);
        }finally{
            if(out != null){
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(),e);
                }
            }
        }
        return R.success(fullFileName);
    }


    /**
     * 删除图片
     *
     * @param filePath
     * @return
     */
    public R<String> delImage(String filePath) {
        if (filePath.indexOf("http://temp/") != -1 && filePath.indexOf("../../") != -1) {
            return R.error(ErrorEnum.PARAMS_ERROR);
        }
        delPool.execute(() -> {
            String subFilePath = basePath + filePath.replaceAll("/file", "");
            boolean delFlag = FileUtil.deleteFile(subFilePath);
            String uploadResizedPath = subFilePath.replaceAll("/images/", "/images-resized/");
            File uploadResizedFile = new File(uploadResizedPath);
            uploadResizedFile.delete();
            if (!delFlag) {
                logger.error("删除图片失败,文件：" + subFilePath);
            }
        });
        return R.success(filePath);
    }

    /**
     * 删除目录
     *
     * @param filePath
     * @return
     */
    public R<String> delFolder(String filePath) {
        delPool.execute(() -> {
            String subFilePath = basePath + filePath.replaceAll("/file", "");
            boolean delFlag = FileUtil.delFolder(subFilePath);
            //删除调整尺寸的图片
            String uploadResizedPath = subFilePath.replaceAll("/images/", "/images-resized/");
            FileUtil.delFolder(uploadResizedPath);

            if (!delFlag) {
                logger.error("删除目录失败,目录：" + subFilePath);
            }
        });
        return R.success(filePath);
    }

    /**
     * 获取上传目录
     *
     * @param module
     * @return
     */
    private String getUploadPath(String module, String folder) {
        String fullPath = "";
        if (StrKit.isBlank(module)) {
            fullPath = env.getProperty("file.images.other");
        } else {
            fullPath = env.getProperty("file.images." + module);
            if (StrKit.isBlank(fullPath)) {
                fullPath = env.getProperty("file.images.other");
            }
        }
        if (StrKit.isNotEmpty(folder)) {
            fullPath += folder + "/";
        }
        return fullPath;
    }




}
